package cn.heyige.backend.controller;

import cn.heyige.backend.algorithm.AccuracyAnalyzer;
import cn.heyige.backend.common.CommResponse;
import cn.heyige.backend.dto.UserDivinationSettingsDTO;
import cn.heyige.backend.entity.DivinationFeedbackDO;
import cn.heyige.backend.entity.DivinationSettingDO;
import cn.heyige.backend.entity.UserDO;
import cn.heyige.backend.exception.BusinessException;
import cn.heyige.backend.exception.ErrorCode;
import cn.heyige.backend.mapper.SettingsMapper;
import cn.heyige.backend.service.FeedbackService;
import cn.heyige.backend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 用户占卜设置控制器
 * 管理用户的个性化占卜设置
 */
@RestController
@RequestMapping("api/settings")
@Slf4j
@Tag(name = "用户占卜设置", description = "管理用户的个性化占卜设置")
@RequiredArgsConstructor
public class SettingsController {
    
    private final UserService userService;
    private final FeedbackService feedbackService;
    private final SettingsMapper  settingsMapper;
    private final AccuracyAnalyzer accuracyAnalyzer;
    
    /**
     * 获取用户占卜设置
     * @param userId 用户ID
     * @return 用户占卜设置
     */
    @GetMapping("/{userId}")
    @Operation(summary = "获取用户占卜设置", description = "获取指定用户的占卜设置和统计信息")
    public CommResponse<UserDivinationSettingsDTO> getUserDivinationSettings(@PathVariable Integer userId) {
        try {
            // 获取用户信息
            UserDO user = userService.getOptById(userId)
                .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND));
            
            // 获取用户占卜设置
            Optional<DivinationSettingDO> settingsOptional = settingsMapper.findByUserId(userId);
            
            // 创建设置DTO
            UserDivinationSettingsDTO settingsDTO = new UserDivinationSettingsDTO();
            settingsDTO.setUserId(user.getId());
            settingsDTO.setUsername(user.getUsername());
            settingsDTO.setBirthLocation(user.getBirthLocation());
            settingsDTO.setCurrentCity(user.getCurrentCity());
            settingsDTO.setGender(user.getGender());
            settingsDTO.setMoodStatus(user.getMoodStatus());
            
            // 如果有设置，使用设置值；否则使用默认值
            if (settingsOptional.isPresent()) {
                DivinationSettingDO settings = settingsOptional.get();
                settingsDTO.setApplyFeedback(settings.getApplyFeedback());
                settingsDTO.setPreferredAiFactor(settings.getPreferredAiFactor());
                settingsDTO.setPreferredAiProvider(settings.getPreferredAiProvider());
            } else {
                // 默认设置
                settingsDTO.setApplyFeedback(true);
                settingsDTO.setPreferredAiFactor(1);
                settingsDTO.setPreferredAiProvider("zhipu");
            }
            
            // 获取统计信息
            long totalDivinations = feedbackService.countByUserId(userId);
            double accuracyRate = accuracyAnalyzer.getUserAccuracyRate(userId);
            
            settingsDTO.setTotalDivinations((int) totalDivinations);
            settingsDTO.setAccuracyRate(accuracyRate);
            
            // 获取最近的反馈记录
            List<DivinationFeedbackDO> recentFeedbacks = accuracyAnalyzer.getUserRecentFeedback(userId, 5);
            settingsDTO.setRecentFeedbacks(recentFeedbacks);
            
            return CommResponse.ok(settingsDTO);
        } catch (Exception e) {
            log.error("获取用户占卜设置失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }
    
    /**
     * 更新用户占卜设置
     * @param settingsDTO 用户占卜设置
     * @return 更新后的用户占卜设置
     */
    @PutMapping
    @Operation(summary = "更新用户占卜设置", description = "更新用户的占卜设置")
    public CommResponse<UserDivinationSettingsDTO> updateUserDivinationSettings(@RequestBody UserDivinationSettingsDTO settingsDTO) {
        try {
            // 获取用户信息
            UserDO user = userService.getOptById(settingsDTO.getUserId())
                .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND));
            
            // 更新用户基本信息
            if (settingsDTO.getCurrentCity() != null) {
                user.setCurrentCity(settingsDTO.getCurrentCity());
            }
            if (settingsDTO.getMoodStatus() != null) {
                user.setMoodStatus(settingsDTO.getMoodStatus());
            }
            
            // 保存用户信息
            userService.save(user);
            
            // 更新或创建用户占卜设置
            DivinationSettingDO settings = settingsMapper.findByUserId(settingsDTO.getUserId())
                .orElse(new DivinationSettingDO());
            
            settings.setUserId(settingsDTO.getUserId());
            if (settingsDTO.getApplyFeedback() != null) {
                settings.setApplyFeedback(settingsDTO.getApplyFeedback());
            }
            
            if (settingsDTO.getPreferredAiFactor() != null) {
                settings.setPreferredAiFactor(settingsDTO.getPreferredAiFactor());
            }
            
            if (settingsDTO.getPreferredAiProvider() != null) {
                settings.setPreferredAiProvider(settingsDTO.getPreferredAiProvider());
            }
            
            // 保存设置
            settingsMapper.insert(settings);
            
            // 返回更新后的设置
            settingsDTO.setBirthLocation(user.getBirthLocation());
            settingsDTO.setGender(user.getGender());
            
            return CommResponse.ok(settingsDTO);
        } catch (Exception e) {
            log.error("更新用户占卜设置失败", e);
            return CommResponse.fail(400, e.getMessage());
        }
    }

}
